# ext.py配置工具, 包括数据库连接、Session中间件等
from redis import Redis
from starlette_session import SessionMiddleware, BackendType
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

# 配置数据库
redis_client = Redis(host='localhost', port=6379, db=0)  # 连接Redis数据库
# 配置数据库模型
# # MySQL 数据库配置
# SQLALCHEMY_DATABASE_URL = "mysql+pymysql://root:201817@127.0.0.1:3306/exer"
#
# engine = create_engine(SQLALCHEMY_DATABASE_URL)
# SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
#
# Base = declarative_base()


# SQLite 数据库配置
SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"

engine = create_engine(
    SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()


# 配置Session中间件
def SessionConfig(app):
    app.add_middleware(
        SessionMiddleware,  # 添加中间件
        secret_key="your_secret_key",  # 密钥
        cookie_name="session_cookie_name",  # 名称
        backend_type=BackendType.redis,  # 后端类型
        backend_client=redis_client  # 后端客户端
    )


# 创建数据库和表
def init_db():
    Base.metadata.create_all(bind=engine)


# 获取数据库会话
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
